#include "RingQueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <pthread.h>
#include <memory>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>

using namespace std;

const char* ops="+-*/%";

void *consumerRoutine(void *args)
{
    //RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while(true)
    {
        // int data=0;
        Task t;
        rq->pop(&t);
        // rq->pop(&data);
        t();
        cout<<"consumer done，处理完成的任务是: "<<t.formatRes()<<endl;
        sleep(1);
    }
}
void *productorRoutine(void *args)
{
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    while(true)
    {
        // int data=rand()%10+1;

        int x=rand()%100;
        int y=rand()%100;
        char op=ops[(x+y)%strlen(ops)];

        // rq->push(data);
        Task t(x,y,op);
        rq->push(t);
        cout<<"productor done，生产的任务是: "<<t.formatArg()<<endl;
        
    }
}
int main()
{
    srand(time(nullptr) ^ getpid());
    // RingQueue<int> *rq=new RingQueue<int>();
    RingQueue<Task> *rq=new RingQueue<Task>();
    //单生产单消费
    // pthread_t c, p;
    // pthread_create(&c, nullptr, consumerRoutine, rq);
    // pthread_create(&p, nullptr, productorRoutine, rq);

    // pthread_join(c, nullptr);
    // pthread_join(p, nullptr);

    //多生产多消费
    pthread_t c[3], p[2];
    for(int i =0;i<3;i++)
    {
        pthread_create(c+i, nullptr, consumerRoutine, rq);
    }
    for(int i =0;i<2;i++)
    {
        pthread_create(p+i, nullptr, productorRoutine, rq);
    }
    
    for(int i =0;i<3;i++)
    {
        pthread_join(c[i], nullptr);
    }
    for(int i =0;i<2;i++)
    {
        pthread_join(p[i], nullptr);
    }
    
    
    delete rq;

    return 0;
}